package org.example.cloud.mygateway;

import jakarta.validation.constraints.NotBlank;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author 宋孟林
 * @description 自定义会员等级的路由规则，按照钻 金 银 和 yaml 配置的会员等级以适配是否可以访问
 * @date: 2025/4/9 19:35
 */
@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config> {
    public MyRoutePredicateFactory() {
        super(MyRoutePredicateFactory.Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(MyRoutePredicateFactory.Config config) {
        return serverWebExchange -> {
            String userType = serverWebExchange.getRequest().getQueryParams().getFirst("userType");
            if (userType == null) {
                return false;
            }
            return userType.equals(config.getUserType());
        };
    }
    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("userType");
    }

    /**
     * 这个类就是我们的路由规则
     */
    public static class Config{
        @Setter@Getter@NotBlank
        private String userType;
    }

}
